package com.thinkit.bigdata.web.controller.perCenter;

import com.thinkit.bigdata.core.ConfigHelper;
import com.thinkit.bigdata.core.util.DateFormatUtil;
import com.thinkit.bigdata.core.util.TaskUtil;
import com.thinkit.bigdata.core.util.es.ESUtil;
import com.thinkit.bigdata.core.util.excel.XlsUtil;
import com.thinkit.bigdata.web.coremet.SystemStatic;
import com.thinkit.bigdata.web.model.bus.BusWorkWithBLOBs;
import com.thinkit.bigdata.web.model.perCenter.PendingTaskModel;
import com.thinkit.bigdata.web.model.result.HtmlResult;
import com.thinkit.bigdata.web.service.perCenter.PerCenterService;
import org.apache.log4j.Logger;
import org.apache.poi.hssf.usermodel.*;
import org.apache.shiro.SecurityUtils;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * 待办任务
 * Created by hccl on 2018/9/4.
 */
@RestController
@RequestMapping("/pending-task")
public class PendingTask {

    private static Logger logger = Logger.getLogger(PendingTask.class);

    @Resource
    private PerCenterService perCenterService;

    @Resource
    private ESUtil esUtil;

    @RequestMapping(value = "/get-data-list", method = RequestMethod.POST)
    public HtmlResult getDataList(HttpServletRequest request) {
        String logTxt = "【获取代办任务信息列表】";
        logger.info(logTxt);
        return perCenterService.getDataList(request);
    }

    @RequestMapping(value = "/export-data-excel", method = RequestMethod.POST)
    public void exportData2Excel(HttpServletRequest request, HttpServletResponse response) {
        String logTxt = "【待办任务导出excel方法】";
        logger.info(logTxt);
        try {
            String workId = request.getParameter("workId");//质检任务名称
            List<BusWorkWithBLOBs> works = perCenterService.getWorks(workId);
            if (works.isEmpty()) {
                return;
            }
            String sortName = request.getParameter("sortName");//录音流水
            String sortOrder = request.getParameter("sortOrder");//录音流水
            BoolQueryBuilder boolQuery = perCenterService.getQuery(request, logTxt);
            List<PendingTaskModel> taskModels = new ArrayList<>();
            //总条数
            Integer sum = SystemStatic.crud.queryQBuilderAllByMes(SystemStatic.AUDIO_ES_INDEX, SystemStatic.AUDIO_ES_TYPE, boolQuery);
            //单词查询条数
            int excleMax = ConfigHelper.getInt("export.data.sheet.max.number", 1000);
            List<Integer> pageTout = TaskUtil.formatSum(sum, excleMax);//todo最后一个数字需要特殊处理:6022
            for (Integer aPageTout : pageTout) {
                List<String> docList = SystemStatic.crud.queryMapQBuilderList(
                        SystemStatic.AUDIO_ES_INDEX,
                        SystemStatic.AUDIO_ES_TYPE,
                        aPageTout,
                        excleMax,
                        boolQuery,
                        SystemStatic.crud.formatCloumn(sortName, SystemStatic.AUDIO_ES_INDEX),
                        sortOrder
                );
                if (docList.isEmpty()) continue;
                taskModels.addAll(esUtil.formatModel(docList, workId));
            }
            if (taskModels.isEmpty()) {
                return;
            }
            logger.info("获取数据条数为：" + taskModels.size());
            //生成excel
            HSSFWorkbook workbook = new HSSFWorkbook();//创建一个xls文档对象
            HSSFSheet sheet = workbook.createSheet();//创建一个工作薄对象
            //设置标题和列名称
            String[] header = {"序号", "质检任务名称", "质检任务类型", "录音流水号", "质检状态", "质检属性", "客户号码",
                    "坐席班组", "坐席工号", "坐席姓名", "通话类型", "通话时长(秒)", "通话开始时间", "通话结束时间"};
            String title = "待办任务信息表";
            XlsUtil.setTableTitleHeader(workbook, sheet, Arrays.asList(header), title);
            //获取表文样式
            HSSFCellStyle tableStyle = XlsUtil.getTableStyle(workbook);
            HSSFRow row2;
            HSSFCell cell2;
            for (int j = 0; j < taskModels.size(); j++) {
                PendingTaskModel taskMode = taskModels.get(j);
                row2 = sheet.createRow(3 + j);
                for (int i = 0; i < header.length; i++) {
                    cell2 = row2.createCell(i);
                    cell2.setCellStyle(tableStyle);
                    switch (i) {
                        case 0:
                            cell2.setCellValue(new HSSFRichTextString((j + 1) + ""));
                            break;
                        case 1:
                            cell2.setCellValue(new HSSFRichTextString(taskMode.getWorkName()));
                            break;
                        case 2:
                            cell2.setCellValue(new HSSFRichTextString(taskMode.getPreQuality() == 0 ? "自动质检" : "专项质检"));
                            break;
                        case 3:
                            cell2.setCellValue(new HSSFRichTextString(taskMode.getSerialNumber()));
                            break;
                        case 4:
                            cell2.setCellValue(new HSSFRichTextString(esUtil.changeState(taskMode.getProStatus())));
                            break;
                        case 5:
                            cell2.setCellValue(new HSSFRichTextString(taskMode.getProFlag() == 0 ? "系统" : "人工"));
                            break;
                        case 6:
                            cell2.setCellValue(new HSSFRichTextString(taskMode.getCustomerNum()));
                            break;
                        case 7:
                            cell2.setCellValue(new HSSFRichTextString(taskMode.getSeatGroup()));
                            break;
                        case 8:
                            cell2.setCellValue(new HSSFRichTextString(taskMode.getSeatId()));
                            break;
                        case 9:
                            cell2.setCellValue(new HSSFRichTextString(taskMode.getSeatName()));
                            break;
                        case 10:
                            cell2.setCellValue(new HSSFRichTextString(taskMode.getCallDirection() == 0 ? "呼入" : "呼出"));
                            break;
                        case 11:
                            cell2.setCellValue(new HSSFRichTextString(taskMode.getHoldDuration() + ""));
                            break;
                        case 12:
                            cell2.setCellValue(new HSSFRichTextString(taskMode.getCallStartTime()));
                            break;
                        case 13:
                            cell2.setCellValue(new HSSFRichTextString(taskMode.getCallEndTime()));
                            break;
                    }
                }
            }
            for (int i = 0; i < header.length; i++) {
                sheet.autoSizeColumn((short) i, true);//自动调整列宽
            }
            String fileName = title + "_" + DateFormatUtil.getNowTime() + ".xls";
            // 清空response
            response.reset();
            response.setContentType("application/vnd.ms-excel");
            response.addHeader("Content-Disposition", "attachment;filename=" + new String(fileName.getBytes(StandardCharsets.UTF_8), StandardCharsets.ISO_8859_1));  //转码之后下载的文件名不会出现中文乱码
            workbook.write(response.getOutputStream());
        } catch (Exception e) {
            e.printStackTrace();
            logger.info(logTxt + "异常");
        }
    }

    @RequestMapping(value = "/get-mes", method = RequestMethod.POST)
    public HtmlResult getMes(HttpServletRequest request) {
        String logTxt = "【代办任务提示标】";
        logger.info(logTxt);
        int userIdentity = (Integer) SecurityUtils.getSubject().getSession().getAttribute("userIdentity");
        String workId = request.getParameter("workId");
        logger.info(logTxt + "userIdentity = " + userIdentity);
        logger.info(logTxt + "workId = " + workId);
        return perCenterService.getMes(request);
    }

    @RequestMapping(value = "/update-data-by-ser", method = RequestMethod.POST)
    public HtmlResult updateDataBySer(HttpServletRequest request) {
        String logTxt = "【批量修改数据为已读】";
        logger.info(logTxt);
        String resMap = request.getParameter("resMap");
        logger.info(logTxt + "resMap = " + resMap);
        try {
            return perCenterService.updateDataBySer(request);
        } catch (IOException e) {
            e.printStackTrace();
            return HtmlResult.failure("修改数据失败");
        }
    }
}
